package com.donger.mes.system.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donger.mes.system.base.entity.MesBaseBom;
import com.donger.mes.system.base.entity.MesBaseLine;
import com.donger.mes.system.base.entity.MesBaseStation;
import com.donger.mes.system.base.mapper.MesBaseStationMapper;
import com.donger.mes.system.base.service.MesBaseLineService;
import com.donger.mes.system.base.service.MesBaseStationService;
import com.donger.common.core.utils.BizException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@AllArgsConstructor
public class MesBaseStationServiceImpl implements MesBaseStationService {

    private final MesBaseLineService mesBaseLineService;

    private final MesBaseStationMapper mesBaseStationMapper;
    @Override
    public IPage<MesBaseStation> page(IPage<MesBaseStation> page, QueryWrapper<MesBaseStation> queryWrapper) {
        return mesBaseStationMapper.selectPage(page,queryWrapper);
    }

    @Override
    public MesBaseStation infoById(Long id) {
        return mesBaseStationMapper.selectById(id);
    }

    @Override
    public MesBaseStation infoByCode(String code) {
        MesBaseStation mesBaseStation = mesBaseStationMapper.selectOne(Wrappers.<MesBaseStation>lambdaQuery()
                .eq(MesBaseStation::getCode, code));
        return mesBaseStation;
    }

    @Override
    public void save(MesBaseStation mesBaseStation) {

        // 校验产线是否正确

        // 校验编码是否重复

        Optional.ofNullable(mesBaseStation.getLineCode()).orElseThrow(() -> new BizException("工位不能为空"));

        MesBaseLine mesBaseLine = mesBaseLineService.infoByCode(mesBaseStation.getLineCode());
        mesBaseStation.setLineName(mesBaseLine.getLineName());


        if(mesBaseStation.getId() == null){
            mesBaseStationMapper.insert(mesBaseStation);
        }else{
            mesBaseStationMapper.updateById(mesBaseStation);
        }
    }


}
